import { useRouter } from "vue-router";
import {
  changeUserPassword,
  getUserInfo,
  changeUserInfo,
} from "@/api/user/user";
import { useUserStore } from "@/store";
import { showNotify } from "vant";
import { computed, onMounted, ref } from "vue";
import { getRegister } from "@/api/login/register";
import { showConfirmDialog } from "vant";
import { getLogin } from "@/api/login/login";

//areaCode逻辑
export const useAreaCodeHandler = () => {
  const router = useRouter();
  const text = ref([
    {
      title: "中国",
      code: "+86",
    },
    {
      title: "香港（中国）",
      code: "+852",
    },
    {
      title: "美国",
      code: "+1",
    },
  ]);
  const goLogin = (id, title) => {
    localStorage.setItem("codeId", id);
    localStorage.setItem("title", title);
    router.back();
  };
  return {
    text,
    goLogin,
  };
};

//修改密码逻辑
export const useChangePasswordHandler = () => {
  const passwordPattern = /^[a-zA-Z0-9][a-zA-Z0-9_]{5,11}$/;
  const router = useRouter();
  const userStore = useUserStore();
  const flag = computed(() => {
    return (
      !passwordPattern.test(oldpassword.value) ||
      !passwordPattern.test(newpassword.value)
    );
  });
  const oldpassword = ref("");
  const newpassword = ref("");
  const userid = userStore.userid;
  const show = ref(false);
  const onSubmit = async () => {
    show.value = true;
    try {
      let res = await changeUserPassword({
        id: userid,
        oldPwd: oldpassword.value,
        newPwd: newpassword.value,
      });
      if (res.status == 0) {
        setTimeout(() => {
          show.value = false;
          userStore.removeUserInfo();
          showNotify({
            type: "success",
            message: "修改密码成功",
          });
          router.replace("/home");
        }, 2000);
      } else {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "danger",
            message: "修改失败,旧密码错误!!!",
          });
        }, 2000);
      }
    } catch (error) {
      if (error)
        showNotify({
          type: "danger",
          message: "网络错误!!!",
        });
    }
  };
  return {
    passwordPattern,
    flag,
    onSubmit,
    show,
    oldpassword,
    newpassword,
  };
};

//修改用户信息
export const useChangeUserInfoHandler = () => {
  const telPattern = /^[1]\d{10}$/;
  const usernamepattern = /^[a-zA-Z][a-zA-Z0-9_]{4,9}$/;
  const router = useRouter();
  const userStore = useUserStore();
  const flag = computed(() => {
    return !telPattern.test(tel.value) || !usernamepattern.test(username.value);
  });
  const username = ref("");
  const tel = ref();
  const userid = userStore.userid;
  const show = ref(false);
  const onSubmit = async () => {
    show.value = true;
    try {
      let res = await changeUserInfo({
        id: userid,
        username: username.value,
        tel: tel.value,
      });
      if (res.status == 0) {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "success",
            message: "修改成功",
          });
          router.replace("/personal");
        }, 2000);
      } else {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "danger",
            message: "修改失败",
          });
        }, 2000);
      }
    } catch (error) {
      if (error)
        showNotify({
          type: "danger",
          message: "网络错误",
        });
    }
  };

  const userInfo = async () => {
    let { data } = await getUserInfo({
      id: userid,
    });
    username.value = data[0].username;
    tel.value = data[0].tel;
  };
  
  onMounted(() => {
    userInfo();
  });

  return {
    telPattern,
    usernamepattern,
    username,
    tel,
    userid,
    show,
    onSubmit,
    flag,
  };
};
//手机号注册
export const useRegisterHandler = () => {
  const router = useRouter();
  const usernamepattern = /^[a-zA-Z0-9]{5,10}$/;
  const passwordPattern = /^[a-zA-Z0-9]{6,12}$/;
  const username = ref("");
  const password = ref("");
  const show = ref(false);
  const onSubmit = async (values) => {
    try {
      let res = await getRegister(values);
      show.value = true;
      if (res.status == 0) {
        setTimeout(() => {
          showNotify({
            type: "success",
            message: "注册成功!!!",
          });
          setTimeout(() => {
            username.value = "";
            password.value = "";
            showConfirmDialog({
              title: "注册成功",
              message: "是否直接登录?",
              beforeClose,
            }).then(() => {
              router.replace("/phonelogin");
            });
          }, 1000);
        }, 2000);
      } else {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "danger",
            message: "注册失败，用户名已注册!!!",
          });
        }, 3000);
      }
    } catch (error) {
      if (error)
        showNotify({
          type: "danger",
          message: "网络错误",
        });
    }
  };
  const beforeClose = (action) =>
    new Promise((resolve) => {
      setTimeout(() => {
        if (action === "confirm") {
          show.value = false;
          resolve(true);
        } else {
          show.value = false;
          resolve(true);
        }
      }, 1000);
    });

  const flag = computed(() => {
    return (
      !passwordPattern.test(password.value) ||
      !usernamepattern.test(username.value)
    );
  });

  return {
    usernamepattern,
    passwordPattern,
    username,
    password,
    show,
    onSubmit,
    flag,
  };
};

//手机号登录
export const useLoginHandler = () => {
  const userStore = useUserStore();
  const router = useRouter();
  const usernamepattern = /^[a-zA-Z][a-zA-Z0-9_]{4,9}$/;
  const passwordPattern = /^[a-zA-Z0-9][a-zA-Z0-9_]{5,11}$/;
  const show = ref(false);
  const flag = computed(() => {
    return (
      !passwordPattern.test(password.value) ||
      !usernamepattern.test(username.value)
    );
  });
  const username = ref("");
  const password = ref("");
  const onSubmit = async (values) => {
    try {
      let res = await getLogin(values);
      console.log(res)
      show.value = true;
      if (res.status == 0) {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "success",
            message: "登录成功!!!",
          });
          router.replace("/home");
          userStore.setUserName(values.username);
          userStore.setToken(res.token);
          userStore.setUserId(res.id);
        }, 2000);
      } else {
        setTimeout(() => {
          show.value = false;
          showNotify({
            type: "danger",
            message: "用户名或密码错误!!!",
          });
        }, 2000);
      }
    } catch (error) {
      if (error)
        showNotify({
          type: "danger",
          message: "网络错误",
        });
    }
  };

  return {
    usernamepattern,
    passwordPattern,
    show,
    flag,
    username,
    password,
    onSubmit,
  };
};
